package com.example.propertymanagement.controller;

import com.example.propertymanagement.dto.OwnerDTO;
import com.example.propertymanagement.entity.Owner;
import com.example.propertymanagement.service.OwnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * OwnerController：业主管理控制器类
 * 处理前端请求，调用 OwnerService 执行业主相关操作
 */
@RestController
@RequestMapping("/api/owners")
public class OwnerController {

    @Autowired
    private OwnerService ownerService;

    /**
     * 获取所有业主信息
     * @return List<OwnerDTO> - 所有业主的信息DTO列表
     */
    @GetMapping
    public List<OwnerDTO> getAllOwners() {
        return ownerService.getAllOwners();
    }

    /**
     * 根据业主ID获取业主信息
     * @param id 业主ID
     * @return 返回业主的DTO信息
     */
    @GetMapping("/{id}")
    public OwnerDTO getOwnerById(@PathVariable Integer id) {
        return ownerService.getOwnerById(id)
                .orElseThrow(() -> new RuntimeException("业主未找到"));
    }

    /**
     * 根据业主姓名查找业主
     * @param memberName 业主姓名
     * @return 返回符合条件的业主DTO列表
     */
    @GetMapping("/search")
    public List<OwnerDTO> searchOwnersByName(@RequestParam String memberName) {
        return ownerService.searchOwnersByName(memberName);
    }

    /**
     * 根据身份证号查找业主
     * @param idCard 业主身份证号
     * @return 返回业主DTO
     */
    @GetMapping("/idCard/{idCard}")
    public OwnerDTO getOwnerByIdCard(@PathVariable String idCard) {
        return ownerService.getOwnerByIdCard(idCard);
    }

    /**
     * 添加新业主
     * @param owner 传入的业主实体
     * @return 保存后的 OwnerDTO
     */
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public OwnerDTO saveOwner(@RequestBody Owner owner) {
        return ownerService.addOwner(owner); // 这里返回的是 DTO 类型
    }

    /**
     * 更新业主信息
     * @param id 业主ID
     * @param ownerDTO 更新后的业主DTO
     * @return 返回更新后的业主DTO
     */
    @PutMapping("/{id}")
    public OwnerDTO updateOwner(@PathVariable Integer id, @RequestBody OwnerDTO ownerDTO) {
        Owner owner = new Owner();  // 创建一个新的Owner对象
        owner.setId(id);
        owner.setMemberName(ownerDTO.getMemberName());
        owner.setContactPhone(ownerDTO.getContactPhone());
        owner.setGender(ownerDTO.getGender());
        owner.setMemberType(ownerDTO.getMemberType());
        owner.setIdCard(ownerDTO.getIdCard());
        owner.setBirthDate(ownerDTO.getBirthDate());
        owner.setOccupation(ownerDTO.getOccupation());
        owner.setRemark(ownerDTO.getRemark());
        owner.setCreateTime(ownerDTO.getCreateTime());
        return ownerService.updateOwner(owner);  // 调用Service层更新业主
    }

    /**
     * 删除业主信息
     * @param id 业主ID
     */
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void deleteOwner(@PathVariable Integer id) {
        ownerService.deleteOwner(id);  // 调用Service层删除业主
    }
}